package com.cssw.fyzb.busi.api.acct;

import com.cssw.fyzb.busi.service.team.TeamService;
import com.cssw.fyzb.busi.service.user.UserService;
import com.cssw.fyzb.busi.util.BizUtil;
import com.cssw.fyzb.core.exception.BizException;
import com.cssw.fyzb.busi.service.acct.RedPackService;
import com.cssw.fyzb.core.model.dodb.User;
import com.cssw.fyzb.core.util.AesUtil;
import com.cssw.fyzb.core.util.StringUtil;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import com.ydn.simplelock.SimpleLock;
import com.ydn.simplelock.SimpleLockFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;

import static com.cssw.fyzb.busi.util.Bizs.ERROR_TRADE_PWD;

/**
 * @Author zhouxu
 * @create 2020-12-23 22:10
 */
@Function(description = "私人红包-发", parameters = {
        @Parameter(name = "userId", type = Type.String, description = "用户标识", required = true),
        @Parameter(name = "otherId", type = Type.String, description = "对方用户标识", required = true),
        @Parameter(name = "money", type = Type.Decimal, description = "红包金额（单位：果子）", required = true),
        @Parameter(name = "title", type = Type.String, description = "标题", required = false),
        @Parameter(name = "tradePwd", type = Type.String, description = "交易密码", required = true),

})
@Component
public class RedPackPersonSend implements Action {

    private static final Logger logger = LoggerFactory.getLogger(RedPackPersonSend.class);

    @Autowired
    private RedPackService redPackService;
    @Autowired
    SimpleLockFactory simpleLockFactory;
    @Autowired
    private UserService userService;

    @Autowired
    TeamService teamService;

    @Override
    public Response execute(Request request) throws Exception {
        if (true){
            return Response.fail("发红包功能暂未开放");
        }

        String tradePwd = request.getString("tradePwd");
        Long userId = request.getLong("userId");
        User user = userService.getById(userId);
        if (StringUtil.isEmpty(user.getTradePwd())) {
            return Response.fail("您还未设置交易密码");
        }
        if (StringUtil.isEmpty(tradePwd)) {
            return Response.fail("请输入密码");
        }
        if (!AesUtil.encode(tradePwd).equals(user.getTradePwd())) {
            return Response.fail("交易密码错误");
        }
        Long otherId = request.getLong("otherId");
        Double money = request.getDouble("money");
        String title = request.getString("title");

        // 获取锁
        SimpleLock lock = simpleLockFactory.getLock("USER_" + userId);

        try {
            lock.acquire();

            compareTeamNum(userId, otherId);

            Long packId = redPackService.createPersonRedPack(userId, otherId, BigDecimal.valueOf(money), title);
            return Response.success().put("data", packId);
        } catch (BizException biz) {
            logger.error(biz.getErrMsg(), biz.getErrCode());
            return Response.fail(biz.getErrMsg(), biz.getErrCode());
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail(e);
        } finally {
            lock.release();
        }
    }

    private void compareTeamNum(Long fromUserId, Long toUserId) {
        int fromTeamNum = teamService.getTeamNum(fromUserId);
        int toTeamNum = teamService.getTeamNum(toUserId);

        if (fromTeamNum > toTeamNum && fromTeamNum - toTeamNum >= 100) {
            BizUtil.exception("团队人数不满足，操作失败！");
        } else if (toTeamNum > fromTeamNum && toTeamNum - fromTeamNum >= 100) {
            BizUtil.exception("团队人数不满足，操作失败！");
        }
    }
}
